#include "priv.h"

#include "rl_cmd.h"

static cmd_vty_t *g_vty= NULL;
static int complete_status;

static char *rl_cmd_generator(const char *text, int state)
{
    (void)text;
    vector vline;
    static char **matched = NULL;
    static int index = 0;

    if (!state)
    {
        index = 0;

        vline = cmd_make_strvec(rl_line_buffer);
        if (vline == NULL)
        {
            return NULL;
        }

        if (rl_end && isspace((int)rl_line_buffer[rl_end - 1]))
        {
            vector_set(vline, '\0');
        }

        matched = cmd_complete_command(vline, g_vty, &complete_status);

        cmd_free_strvec (vline);
    }

    if (matched && matched[index])
    {
        return matched[index++];
    }

    return NULL;
}

static char **rl_cmd_completion(const char *text, int start, int end)
{
    (void)start;
    (void)end;
    char **matches = (char **)NULL;

    matches = rl_completion_matches(text, rl_cmd_generator);

#if 0
    if (matches)
    {
        rl_point = rl_end;
        if (complete_status == CMD_COMPLETE_FULL_MATCH)
        {
            rl_pending_input = ' ';
        }
    }
#endif

    return matches;
}


static char *rl_cmd_completion_entry_func(const char *text, int state)
{
    (void)text;
    (void)state;
    return NULL;
}

void rl_cmd_loop(cmd_vty_t *vty)
{
    char *line;

    for ( ; ; )
    {
        line = readline(cmd_prompt(vty));
        add_history(line);
        cmd_execute(vty, line);
        free(line);
        if (vty->status == VTY_CLOSE)
        {
            break;
        }
    }
}

void rl_cmd_init(cmd_vty_t *vty)
{
    g_vty = vty;

    rl_completion_entry_function = rl_cmd_completion_entry_func;
    rl_attempted_completion_function = rl_cmd_completion;
    rl_completion_append_character = '\0';
}

